package com.netease.cloud.cm.util;

import lombok.extern.slf4j.Slf4j;
import retrofit2.Response;

import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

/**
 * 接口回滚操作
 */
@Slf4j
public class Defer {

    private List<DeferFunc> funcs = new LinkedList<>();

    public void add(DeferFunc func) {
        funcs.add(func);
    }

    public void run() {
        Collections.reverse(funcs);
        funcs.forEach(func -> {
            for (int i = 0; i < 3; i++) {
                try {
                    Response result = func.run().execute();
                    assert result.code() == 200 || result.code() == 404;
                    break;
                } catch (Throwable e) {
                    log.error("Defer run with error", e);
                }
            }
        });
    }
}
